package lslnx;

import lslnx.model.User;
import lslnx.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by lslnx on 2017/4/25.
 */
@Component
public class MyRealm extends AuthorizingRealm{

    @Autowired
    private UserService userService;

    /**
     * 授权
     * @param principals
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 登录验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName = (String) token.getPrincipal();
        User user = userService.selectUserInfoByLoginName(userName);
        AuthenticationInfo info = null;
        if(user != null) {
            String password = new String((char[]) token.getCredentials());
            if (password.equals(user.getLoginPw())) {
                info = new SimpleAuthenticationInfo(userName, password, getName());
            }else{
                throw new IncorrectCredentialsException("密码错误");
            }

        }else{
            throw new UnknownAccountException("用户不存在");
        }
       /* String passWord = new String ((char[]) token.getCredentials());
        if(!"zhang".equals(userName)){
            throw new UnknownAccountException("用户不存在");
        }
        if(!"123".equals(passWord)){
            throw new IncorrectCredentialsException("密码错误");
        }*/
        return info;
    }
}
